extends Node

const MAX_RANGE = 150#攻击范围
const  BASIC_DAMAGE = 5#基础伤害

@export var sword_ability: PackedScene#剑能力
@onready var timer = $Timer

var damage_percent: float = 1.0#伤害百分比
var base_wait_time = 0#攻击频率

func _ready() -> void:
	base_wait_time = timer.wait_time
	timer.timeout.connect(on_timer_timeout)
	get_parent().sword_upgrade.connect(on_ability_upgrade_added)
	pass

#计时器结束发起攻击
func on_timer_timeout() -> void:
	timer.start()
	var player = get_tree().get_first_node_in_group("player")
	if player == null:
		return
	var enemis = get_tree().get_nodes_in_group("enemy")
	enemis = enemis.filter(func(enemy: Node2D):#寻找范围内的敌人
		return enemy.global_position.distance_squared_to(player.global_position) < pow(MAX_RANGE,2)
		)
	if !enemis.size():
		return
	enemis.sort_custom(func(a: Node2D,b: Node2D):#将范围内的敌人按距离排序
		var a_distance = a.global_position.distance_squared_to(player.global_position)
		var b_distance = b.global_position.distance_squared_to(player.global_position)
		return a_distance < b_distance
		)
	var sword_instance = sword_ability.instantiate()#实例化剑去攻击敌人
	self.get_tree().get_first_node_in_group("foreground_layer").add_child(sword_instance)
	sword_instance.hitbox_component.damage = BASIC_DAMAGE * damage_percent
	sword_instance.global_position = enemis[0].global_position
	sword_instance.global_position += Vector2.RIGHT.rotated(randf_range(0,TAU)) * 4
	var enemise_direction = enemis[0].global_position - sword_instance.global_position
	sword_instance.rotation = enemise_direction.angle()
	pass	

#能力升级时使之生效
func on_ability_upgrade_added(upgrade: AbilityUpgrade, current_upgrade: Dictionary) -> void:
	if upgrade.id == "sword_rate":
		var rate_add = 1 + current_upgrade[upgrade.id]["quantity"] * .1
		rate_add = min(rate_add, 2.0)
		timer.wait_time = snapped(base_wait_time / rate_add, 0.01)
	elif upgrade.id == "sword_damage":
		damage_percent = 1 + current_upgrade[upgrade.id]["quantity"] * .2
	pass
